package com.wzh.project.thread.threadpool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.wzh.project.thread.basethread.MyThread1;
/**
 * 四种线程池
 * @author wzh
 *
 */
public class TestMain {
	private static final Logger logger=LogManager.getLogger(TestMain.class);
	
	public static void main(String[] args) throws Exception {
//		Executors.newCachedThreadPool();
//		Executors.newFixedThreadPool(10);
//		Executors.newScheduledThreadPool(10);
//		Executors.newSingleThreadExecutor();
//		Executors.newSingleThreadScheduledExecutor();
//		Executors.newWorkStealingPool();
//		TimerTask
		TestMain test=new TestMain();
		//缓存线程池
		//test.cachedThreadPool();
		//固定容量线程池
		//test.fixedThreadPool();
		//定期执行
		//test.scheduledThreadPool();
		//单一线程池
		test.singleThreadExecutor();
		
	}
	
	/**
	 * 缓存连接池
	 * @throws InterruptedException 
	 */
	public void cachedThreadPool() throws InterruptedException {
		ExecutorService executorService =Executors.newCachedThreadPool();
		for (int i = 0; i < 5; i++) {
			executorService.execute(new MyThread1());
			Thread.sleep(1000);//让上一个线程执行完毕
		}
		for (int i = 0; i < 5; i++) {//很有可能上一个线程还没有执行完
			executorService.execute(new MyThread1());
		}
	}
	/**
	 * 定长线程池
	 * @throws Exception
	 */
	public void fixedThreadPool() throws Exception{
		ExecutorService executorService =Executors.newFixedThreadPool(5);
		for (int i = 0; i < 10; i++) {
			executorService.execute(new MyThread1());
		}
	}
	/**
	 * 延时多长时间执行
	 * @throws Exception
	 */
	public void scheduledThreadPool() throws Exception{
		System.out.println("==");
		ScheduledExecutorService executorService=Executors.newScheduledThreadPool(10);
		executorService.execute(new MyThread1());
		//第一个参数设定的需要执行的线程
		//第二个延迟多长时间执行
		//第三个两次执行时间的间隔（周期）
		//执行的单位 秒/分钟/天 等等
		executorService.scheduleAtFixedRate(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				logger.debug("==run==");
			}
		}, 2000, 5000, TimeUnit.MILLISECONDS);
	}
	
	/**
	 * 全局唯一 一个线程进行执行//先进先出
	 * @throws Exception
	 */
	public void singleThreadExecutor() throws Exception{
		ExecutorService executorService=Executors.newSingleThreadExecutor();
		for (int i = 0; i < 5; i++) {
			executorService.execute(new Runnable() {
				
				@Override
				public void run() {
					logger.debug("start=");
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			});
		}
	}
}
